const Usecase = require('../../shared/usecase/Usecase')
const { RoleNotFoundError } = require('../../domain/role/error')
const R = require('ramda')

const notUpdateFields = ['code']

class UpdateRole extends Usecase {
  constructor({ roleRepo, database, currentUser }) {
    super()
    this.roleRepo = roleRepo
    this.sequelize = database.sequelize
    this.currentUser = currentUser
  }
  async execute(data) {
    const role = await this.roleRepo.findById(data.id)
    if (!role) throw new RoleNotFoundError(data)
    const transaction = await this.sequelize.transaction()
    try {
      Object.assign(role, R.omit(notUpdateFields, data))
      await role.validate()
      await this.roleRepo.update(role, {
        transaction,
        currentUser: this.currentUser,
      })
      await transaction.commit()
    } catch (e) {
      await transaction.rollback()
      throw e
    }
  }
}

module.exports = UpdateRole
